package com.xuxu.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuxu.blog.dao.RoleDao;
import com.xuxu.blog.dao.UserDao;
import com.xuxu.blog.entity.InfoEntity;
import com.xuxu.blog.entity.PermissonEntity;
import com.xuxu.blog.entity.UserEntity;
import com.xuxu.blog.entity.bean.UserInfo;
import com.xuxu.blog.service.UserService;
import com.xuxu.blog.utils.MD5Utils;
import com.xuxu.blog.utils.TokenUtils;
import com.xuxu.common.utils.PageUtils;
import com.xuxu.common.utils.Query;
import com.xuxu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Map;


@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Resource
    private UserDao userDao;
    @Resource
    private InfoServiceImpl infoService;
    @Resource
    private RoleDao roleDao;
    @Resource
    private PermissonServiceImpl permissonService;
    @Resource
    private HttpServletRequest request;
    @Autowired
    UserService userService;

    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );
        List<UserEntity> records = page.getRecords();
        for (int i = 0; i < records.size(); i++) {
            if (records.get(i).getRole().equals(1)) {
                records.get(i).setRoleName("管理员");
            } else {
                records.get(i).setRoleName("普通用户");
            }
        }
        page.setRecords(records);
        return new PageUtils(page);
    }

    /**
     * 通过手机号进行验证
     * @param userEntity
     * @return
     */
    public UserEntity query(UserEntity userEntity) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<UserEntity>();
        wrapper.eq("phone", userEntity.getPhone());
        return userDao.selectOne(wrapper);
    }

    /**
     * 通过传统方式基于用户名查询到的数据和表单密码进行比对
     * @param user
     * @return
     */
    public R Login(UserEntity user) {
        // 设置查询条件：通过用户名查询真实信息（主要是密码）。
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        log.debug("userentity:{}",user);
        wrapper.eq("username", user.getUsername());
        // 获取到真实信息：第一次查询数据库
        UserEntity userEntity = userDao.selectOne(wrapper);
        if (userEntity == null) {
            return R.error("您还没有注册呢，请先注册！");
        }
        String md5password = MD5Utils.md5(user.getPassword());
        if (!md5password.equals(userEntity.getPassword())) {
            return R.error("密码错误");
        }
        // 设置并存储token信息
        String token = TokenUtils.genToken(userEntity.getId().toString(), userEntity.getPassword());
        userEntity.setToken(token);
        // 设置当前用户的登录信息并回传
        InfoEntity infoEntity = infoService.saveCurrentInfo(userEntity);
        // 设置相关权限
        HashSet<PermissonEntity> allPermission = permissonService.getAllPermission(userEntity);
        userEntity.setPermissions(allPermission);
        UserInfo userInfo = new UserInfo(userEntity);

        userInfo.setIp(infoEntity.getIp());
        userInfo.setIpAddress(infoEntity.getAddr());
        return R.ok("20000").put("data", userInfo);
    }

    /**
     * 直接通过手机号验证登录
     * @param phone
     * @return
     */
    public R LoginByPhone(String phone) {
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", phone);
        UserEntity query = userDao.selectOne(wrapper);
        log.error("通过手机号查询数据库的数据是：{}", query);
        // 当前用户为新用户，直接注册一个身份
        if (query==null) {
            query.setPhone(phone);
            query.setAddress("地球");
            query.setPassword(MD5Utils.md5("123456"));
            query.setRole(2);
            query.setPoints(0);
            query.setNick("起个昵称吧");
            query.setAvatar("http://tamad.fun:9001/images/2022/08/25/202208251629184.jpg");
            userService.save(query);
        }
        // 设置并存储token信息
        String token = TokenUtils.genToken(query.getId().toString(), query.getPassword());
        query.setToken(token);

        // 设置当前用户的登录信息
        infoService.saveCurrentInfo(query);

        // 设置相关权限
        HashSet<PermissonEntity> allPermission = permissonService.getAllPermission(query);
        query.setPermissions(allPermission);
        UserInfo userInfo = new UserInfo(query);
        return R.ok("20000").put("data", userInfo);

    }

    /**
     * 通过stream判断是否为空
     * @param username
     */
    public void queryByStream(String username) {
        List<UserEntity> list = userDao.selectList(null);
        long count = list.stream().filter(u -> username.equals(u.getUsername())).count();
        System.out.println(count);
    }

    /**
     * 通过邮件验证码注册
     * @param user
     * @return
     */
    public boolean register(UserEntity user) {
        UserEntity entity = userDao.selectOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getUsername, user.getUsername()));
        if (entity != null) {
            return false;
        }
        user.setPassword(MD5Utils.md5(user.getPassword()));
        userDao.insert(user);
        return true;
    }
}